<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <div>
            <el-input
              v-model="queryData.query"
              @clear="getUserList"
              clearable
              placeholder="请输入内容"
              class="input-with-select"
            >
              <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="5">
          <div>
            <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table border :data="userList" stripe style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="item">
            <el-switch
              v-model="item.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="editSwitch(item.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope" width="180">
            <el-button
              @click="editUser(scope.row.id)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              @click="removeUser(scope.row.id)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
            ></el-button>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                @click="showRolesDialog(scope.row)"
                size="mini"
                type="warning"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[2, 4, 8, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- //添加用户表单验证 -->
    <el-dialog @close="resetAdd" title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!-- //将span改成验证表单的组件 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- prop属性是校验规则 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- //编辑用户表单验证 -->
    <el-dialog @close="resetEdit" title="编辑用户" :visible.sync="editDialogVisible" width="50%">
      <!-- //将span改成验证表单的组件 -->
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- prop属性是在editRules中找到对应的校验规则 -->
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserConfirm">确 定 修 改</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色按钮点击显示的对话框 -->
    <el-dialog title="提示" :visible.sync="setRolesDialogVisible" width="50%">
      <!-- 对话框里显示树形控件 -->
      <span>当前用户名：{{userInfo.username}}</span>
      <span>当前角色：{{userInfo.role_name}}</span>
      {{activeOpt}}
      <!-- activeOpt会自动赋值为value -->
      <el-select v-model="activeOpt" placeholder="请选择">
        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRolesSub()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //自定义邮箱验证规则 放在data函数中return的前面 因为return的都是数据 正则表达式使用谷歌FE插件
    // 函数设置三个参数 第二个为表单里要验证的值 第三个为回调函数 匹配成功直接返回cb即可 匹配失败调用cb时携带一个错误信息
    const checkEmail = (rule, value, callback) => {
      var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if (reg.test(value)) {
        return callback();
      }
      callback(new Error("邮箱格式不正确"));
    };
    // 自定义手机号格式验证
    const checkMobile = (rule, value, callback) => {
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(value)) {
        return callback();
      }
      callback(new Error("手机号码格式不正确"));
    };

    return {
      //查询用户列表需要的参数
      queryData: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      //控制添加用户表单显示或隐藏
      addDialogVisible: false,

      //添加用户表单验证属性addForm用来存储表单渲染和提交的内容 这里有默认值
      // 及其对应的规则addRules
      addForm: {
        username: "zs",
        password: "123456",
        email: "123@qq.com",
        mobile: "13388888888"
      },
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 7, message: "长度在2到7个字符之间", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用密码", trigger: "blur" },
          { min: 5, max: 7, message: "长度在5到7个字符之间", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 自定义的校验规则通过validator引用 放在data中
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },

      //控制编辑用户表单显示或隐藏
      editDialogVisible: false,
      //定义一个对象用来存储当前编辑状态的用户数据 用于渲染到表单中
      editForm: {},
      //编辑用户表单验证属性addForm及其对应的规则addRules
      editRules: {
        email: [
          //多条校验规则
          { required: true, message: "请输入邮箱", trigger: "blur" },
          // 自定义的校验规则通过validator引用 放在data中
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },

      //控制分配权限对话框是否显示
      setRolesDialogVisible: false,

      //存储 点击权限分配时 获取的row 当前用户信息
      userInfo: {},

      //获取的所有角色信息
      roleList: [],

      // activeOpt为elementUI中select组件中的v-model的值 会自动绑定 组件中的：value 即选中的当前觉得的id
      activeOpt: ""
    };
  },

  methods: {
    //定义方法获取数据
    async getUserList() {
      //获取数据
      var res = await this.axios.get("users", {
        params: this.queryData
      });
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取失败");
      //获取成功 就将需要的数据保存到变量中
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //修改状态按钮
    async editSwitch(row) {
      console.log(row);
      var res = await this.axios.put(`users/${row.id}/state/${row.mg_state}`);
      console.log(res);
      if (res.meta.status == 200) {
        this.$message.success("修改成功");
      }
    },
    //每页多少条 改变时触发
    handleSizeChange(val) {
      console.log(val);
      this.queryData.pagesize = val;
      //改变了pagesize之后要重新渲染数据
      this.getUserList();
    },
    //改变当前页时触发
    handleCurrentChange(val) {
      console.log(val);
      this.queryData.pagenum = val;
      //改变了pagenum之后要重新渲染数据
      this.getUserList();
    },

    //点击关闭重置添加用户表单的事件
    resetAdd() {
      this.$refs.addForm.resetFields();
    },
    //点击关闭重置编辑用户表单的事件
    resetEdit() {
      //前提是form表单上要有ref="editForm"是个属性 resetFields()为eleUI的表单重置方法
      this.$refs.editForm.resetFields();
    },
    //添加用户表单点击确定按钮做两件事 校验表单并发送请求
    addUser() {
      this.$refs.addForm.validate(async flag => {
        // flag为true校验成功之后发送请求
        // console.log(flag);
        if (!flag) return; //失败 退出函数
        //成功发送请求
        var res = await this.axios.post("users", this.addForm);
        console.log(res);

        if (res.meta.status == 201) {
          this.$message.success("创建成功");
          this.addDialogVisible = false;
          this.getUserList();
        } else {
          console.log(res.meta.msg);

          this.$message.error("创建失败");
        }
      });
    },

    //点击表单中的编辑按钮 编辑表单显示
    async editUser(id) {
      this.editDialogVisible = true;
      //编辑表单显示后 获取当前用户的数据到表单中
      var res = await this.axios.get("users/" + id);
      // 将结果保存到一个对象中 去data中定义一个对象
      this.editForm = res.data;
    },
    // 修改后点击确认编辑按钮 校验并发送请求
    editUserConfirm() {
      //先校验表单
      this.$refs.editForm.validate(async flag => {
        if (!flag) return;
        //发送请求 这里请求的第二个参数也可以直接传addForm对象 但接口不需要那么多的数据 容易出错
        var res = await this.axios.put("users/" + this.addForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        });
        if (res.meta.status == 200) {
          //请求成功 提示+隐藏对话框+重新更新表单
          this.$message.success(res.meta.msg);
          this.editDialogVisible = false;
          this.getUserList();
        }
      });
    },

    //点击删除用户触发确认删除提示框
    removeUser(id) {
      this.$cfm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          //确定发送请求删除用户
          var res = await this.axios.delete("users/" + id);
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
            //删除成功 重新渲染页面
            this.getUserList();
          } else {
            this.$message.error(res.meta.msg);
          }
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },

    async showRolesDialog(row) {
      this.userInfo = row;
      console.log(this.userInfo);
      this.setRolesDialogVisible = true;
      var res = await this.axios.get("roles");
      if (res.meta.status == 200) {
        //若请求成功 将获取到的所有角色列表res.data存储到roleList中
        this.roleList = res.data;
        console.log(this.roleList);
      }
    },

    // 在分配权限按钮对话框中点击确定按钮
    async setRolesSub() {
      //没有选择新角色 return
      if (!this.activeOpt) return
      // 分配用户新的角色 需要传递两个参数 用户id和角色id
      var res = await this.axios.put(`users/${this.userInfo.id}/role`, {
        rid: this.activeOpt
      });
      console.log(res);
      if (res.meta.status == 200) {
        this.$message.success("更改用户角色成功");
        this.setRolesDialogVisible = false;
        this.getUserList()
      }
    }
  },

  created() {
    this.getUserList();
  }
};
</script>

<style lang='less' scoped>
.el-table {
  margin-top: 20px;
}
</style>
